package com.rongshu;

import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.multidex.MultiDexApplication;
import android.view.Gravity;

import com.rongshu.api.FileUploadService;
import com.rongshu.api.RetorfitService;
import com.rongshu.base.BuildConfig;
import com.rongshu.utils.UserInfoUtils;
import com.rongshu.view.home.entity.ArticleItem;
import com.rongshu.widget.AudiobookFloatWindow;
import com.rongshu.widget.SmartRefreshFooter;
import com.rongshu.widget.SmartRefreshHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreater;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreater;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.socialize.PlatformConfig;
import com.utils.DensityUtil;
import com.utils.LogUtil;
import com.utils.SPUtils;
import com.utils.TypeFaceUtils;
import com.widget.toast.ToastUtils;
import com.widget.toast.style.ToastQQStyle;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import cn.jpush.android.api.JPushInterface;

public class App extends MultiDexApplication {

    public static Context sContext;

    private List<Activity> oList;//用于存放所有启动的Activity的集合
    protected AudiobookFloatWindow floatWindow;
    protected int actCount = 0;
    //播放音频是否允许使用蜂窝网络
    protected boolean userPhoneNetwork = false;
    //首页文章
    private List<ArticleItem> list = null;

    @Override
    public void onCreate() {
        super.onCreate();
        myApplication = this;
        sContext = getApplicationContext();
        //初始化请求
        RetorfitService.init();
        FileUploadService.init();
        //SharedPreferences
        SPUtils.init(this);
        //activty
        oList = new ArrayList<Activity>();
        LogUtil.init(BuildConfig.IS_DEBUG, "rongshu-->");
        //初始化友盟
        initUMeng();
        //初始化极光推送
        initJPush();
        //默认字体
        TypeFaceUtils.initTypeFace(this, TypeFaceUtils.PINGFANG_FINE);
        //toast
        ToastUtils.init(this, new ToastQQStyle());
        //android p
        closeAndroidPDialog();
        registerActivityLifeCallback();
//        if (LeakCanary.isInAnalyzerProcess(this)) {
//            // This process is dedicated to LeakCanary for heap analysis.
//            // You should not init your app in this process.
//            return;
//        }
//        LeakCanary.install(this);
    }


    private void initUMeng() {
        PlatformConfig.setWeixin(BuildConfig.WEIXIN_APPID, BuildConfig.WEIXIN_SECRET);
        PlatformConfig.setSinaWeibo(BuildConfig.WEIBO_APPKEY, BuildConfig.WEIBO_SECRET, "");
        PlatformConfig.setQQZone(BuildConfig.QQ_APPID, BuildConfig.QQ_APPKEY);
        UMConfigure.init(this, BuildConfig.UMENG_KEY, null, UMConfigure.DEVICE_TYPE_PHONE, "");
        /**
         * 设置组件化的Log开关
         * 参数: boolean 默认为false，如需查看LOG设置为true
         */
        UMConfigure.setLogEnabled(BuildConfig.IS_DEBUG);
        MobclickAgent.setScenarioType(this, MobclickAgent.EScenarioType.E_UM_NORMAL);
    }

    public static Context getContext() {
        return sContext;
    }

    static {//static 代码段可以防止内存泄露
        SmartRefreshLayout.setDefaultRefreshHeaderCreater(new DefaultRefreshHeaderCreater() {
            @Override
            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
                //设置全局的Header构建器
                return new SmartRefreshHeader(context).setSpinnerStyle(SpinnerStyle.Translate);
            }
        });

        SmartRefreshLayout.setDefaultRefreshFooterCreater(new DefaultRefreshFooterCreater() {
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
                //指定为经典Footer，默认是 BallPulseFooter
                return new SmartRefreshFooter(context).setSpinnerStyle(SpinnerStyle.Translate);
            }
        });
    }

    private void initJPush() {
        JPushInterface.setDebugMode(BuildConfig.IS_DEBUG);
        JPushInterface.init(getApplicationContext());
        String registrationID = JPushInterface.getRegistrationID(getApplicationContext());
        UserInfoUtils.saveRegistrationId(registrationID);
    }

    /**
     * 去掉在Android P上的提醒弹窗
     */
    private void closeAndroidPDialog() {
        if (Build.VERSION.SDK_INT >= 28) {
            try {
                Class aClass = Class.forName("android.content.pm.PackageParser$Package");
                Constructor declaredConstructor = aClass.getDeclaredConstructor(String.class);
                declaredConstructor.setAccessible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                Class cls = Class.forName("android.app.ActivityThread");
                Method declaredMethod = cls.getDeclaredMethod("currentActivityThread");
                declaredMethod.setAccessible(true);
                Object activityThread = declaredMethod.invoke(null);
                Field mHiddenApiWarningShown = cls.getDeclaredField("mHiddenApiWarningShown");
                mHiddenApiWarningShown.setAccessible(true);
                mHiddenApiWarningShown.setBoolean(activityThread, true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 全局监听生命周期
     */
    protected void registerActivityLifeCallback() {
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {

            }

            @Override
            public void onActivityStarted(Activity activity) {
                actCount++;
                if (floatWindow != null) {
                    showFloatWindow();
                }
            }

            @Override
            public void onActivityResumed(Activity activity) {
            }

            @Override
            public void onActivityPaused(Activity activity) {
            }

            @Override
            public void onActivityStopped(Activity activity) {
                actCount--;
                if (actCount <= 0) {
                    hideFloatWindow();
                }
            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

            }

            @Override
            public void onActivityDestroyed(Activity activity) {

            }
        });
    }

    /**
     * 显示迷你悬浮窗
     */
    public void showFloatWindow() {
        if (floatWindow == null) {
            floatWindow = new AudiobookFloatWindow(getApplicationContext());
            floatWindow.setGravity(Gravity.BOTTOM | Gravity.RIGHT,
                    30, DensityUtil.getScreenHeight(this) / 9);
            floatWindow.setMoreRange(DensityUtil.getScreenHeight(this) - 200,
                    DensityUtil.getScreenHeight(this) / 14);
            floatWindow.setCloseListener(new AudiobookFloatWindow.CloseMiniWindowListener() {
                @Override
                public void close() {
                    floatWindow.clear();
                    floatWindow = null;
                }
            });
            floatWindow.show();
        } else {
            floatWindow.show();
        }
    }

    /**
     * 隐藏迷你悬浮窗
     */
    public void hideFloatWindow() {
        if (floatWindow != null) {
            floatWindow.dimiss();
        }
    }

    /**
     * 清空迷你悬浮窗
     */
    public void clearFloatWindow() {
        if (floatWindow != null) {
            floatWindow.clear();
            floatWindow = null;
        }
    }

    /**
     * 刷新悬浮窗
     */
    public void updateFloatWindow(boolean isExpand) {
        if (floatWindow != null) {
            floatWindow.updateViewVisible(isExpand);
        }
    }

    /**
     * 更新悬浮窗封面
     */
    public void updateFloatWindowCover(String url) {
        if (floatWindow != null) {
            floatWindow.updateCoverImg(url);
        }
    }

    public AudiobookFloatWindow getFloatWindow() {
        return floatWindow;
    }

    public boolean getUserPhoneNetwork() {
        return userPhoneNetwork;
    }

    public void setUserPhoneNetwork(boolean userPhoneNetwork) {
        this.userPhoneNetwork = userPhoneNetwork;
    }

    /**
     * 添加Activity
     */
    public void addActivity(Activity activity) {
        // 判断当前集合中不存在该Activity
        if (!oList.contains(activity)) {
            oList.add(activity);//把当前Activity添加到集合中
        }
    }

    /**
     * 销毁所有的Activity
     */
    public void removeALLActivity() {
        clearFloatWindow();
        setUserPhoneNetwork(false);
        //通过循环，把集合中的所有Activity销毁
        for (Activity activity : oList) {
            activity.finish();
        }
        oList.clear();
    }

    /**
     * 销毁所有的Activity
     */
    public void removeActivity(Activity activity) {
        //删除集合中的activity
        if (oList.contains(activity)) {
            oList.remove(activity);
        }
    }

    private static App myApplication = null;

    public static App getApplication() {
        return myApplication;
    }

    /**
     * 设置首页数据
     */
    public void setList(List<ArticleItem> list) {
        this.list = list;
    }

    /**
     * 获取首页数据
     */
    public List<ArticleItem> getList() {
        return list;
    }
}
